package com.lpf.MyGameSaveBackup.GameSaveBackup.controller;

import cn.hutool.core.collection.CollUtil;
import com.lpf.MyGameSaveBackup.GameSaveBackup.service.GameSaveBackupService;
import com.lpf.MyGameSaveBackup.GameSaveBackup.vo.GameSaveBackVo;
import com.lpf.MyGameSaveBackup.config.service.GlobalConfigService;
import com.lpf.MyGameSaveBackup.config.vo.GlobalConfigVo;
import com.lpf.MyGameSaveBackup.utils.AlertUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;

public class MainController {

    @FXML
    private ListView<GameSaveBackVo> gameList;
    @FXML
    private TableColumn<GameSaveBackVo, String> gameNameColumn;
    @FXML
    private TableColumn<GameSaveBackVo, String> gameSavePathColumn;
    @FXML
    private TableColumn<GameSaveBackVo, String> backupPathColumn;

    @FXML
    private Button addButton;
    @FXML
    private Button editButton;
    @FXML
    private Button deleteButton;
    @FXML
    private Button backupButton;
    @FXML
    private Button syncButton;

    private ObservableList<GameSaveBackVo> gameDataList = FXCollections.observableArrayList();

    // 初始化方法修改
    @FXML
    public void initialize() {
        // 初始化列表视图和单元格工厂
        gameList.setCellFactory(param -> new ListCell<GameSaveBackVo>() {
            @Override
            protected void updateItem(GameSaveBackVo item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setGraphic(null);
                    setText(null);
                } else {
                    try {
                        // 加载列表项FXML
                        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/GameListItem.fxml"));
                        HBox cell = loader.load();

                        // 设置数据
                        javafx.scene.control.Label gameNameLabel = (javafx.scene.control.Label) cell.lookup("#gameName");
                        javafx.scene.control.Label savePathLabel = (javafx.scene.control.Label) cell.lookup("#savePath");
                        javafx.scene.control.Label backupPathLabel = (javafx.scene.control.Label) cell.lookup("#backupPath");


                        gameNameLabel.setText(item.getGameName());
                        savePathLabel.setText("本地路径: " + item.getGameSavePath());
                        backupPathLabel.setText("备份路径: " + item.getBackupPath());

                        // 设置默认图标（确保资源目录下有此图片）
                        Image defaultIcon = new Image(getClass().getResourceAsStream("/static/icon/Logo.png"));
                        ImageView gameIcon = (ImageView) cell.lookup("#gameIcon");
                        String iconUrl = item.getGameIconUrl();
                        if (iconUrl != null && !iconUrl.isEmpty()) {
                            // 加载图标（支持本地资源或网络URL）
                            Image iconImage = new Image(iconUrl, true); // 异步加载
                            // 处理加载失败（用默认图标兜底）
                            iconImage.errorProperty().addListener((obs, oldVal, newVal) -> {
                                if (newVal) {
                                    gameIcon.setImage(defaultIcon);
                                }
                            });
                            gameIcon.setImage(iconImage);
                        } else {
                            // 无图标时使用默认图
                            gameIcon.setImage(defaultIcon);
                        }

                        setGraphic(cell);
                    } catch (IOException e) {
                        e.printStackTrace();
                        setText(item.getGameName()); // 出错时显示文本 fallback
                    }
                }
            }
        });

        // 绑定数据集合到列表
        gameList.setItems(gameDataList);

        // 加载保存的游戏数据
        loadGames();

        // 更新按钮状态绑定（从gameTable改为gameList）
        editButton.disableProperty().bind(gameList.getSelectionModel().selectedItemProperty().isNull());
        deleteButton.disableProperty().bind(gameList.getSelectionModel().selectedItemProperty().isNull());
        backupButton.disableProperty().bind(gameList.getSelectionModel().selectedItemProperty().isNull());
        syncButton.disableProperty().bind(gameList.getSelectionModel().selectedItemProperty().isNull());
    }

    private void loadGames() {
        GlobalConfigService.refreshGlobalConfig();
        if (null != GlobalConfigService.GlobalConfig && CollUtil.isNotEmpty(GlobalConfigService.GlobalConfig.getGameSaveBackVoList())){
            gameDataList.addAll(GlobalConfigService.GlobalConfig.getGameSaveBackVoList());
        }
    }

    @FXML
    private void handleAddGame() {
        try {
            FXMLLoader loader = new FXMLLoader(MainController.class.getResource("/fxml/gameDialog.fxml"));
            Parent root = loader.load();

            GameDialogController controller = loader.getController();
            Stage dialogStage = new Stage();
            controller.setDialogStage(dialogStage);
            // 关键：设置弹窗大小（宽450，高350，可按需调整）
            dialogStage.setWidth(450);  // 弹窗宽度
            dialogStage.setHeight(250); // 弹窗高度
            // 可选：设置最小/最大尺寸，防止拉伸过度
            dialogStage.setMinWidth(450);
            dialogStage.setMaxWidth(450);
            dialogStage.setMinHeight(250);
            dialogStage.setMaxHeight(250);

            // 其他配置（标题、模态、所有者）
            dialogStage.setTitle("添加游戏");
            dialogStage.setScene(new Scene(root));
            dialogStage.initModality(Modality.WINDOW_MODAL);
            dialogStage.initOwner(addButton.getScene().getWindow());

            dialogStage.showAndWait();

            if (controller.isOkClicked()) {
                GameSaveBackVo game = controller.getGame();
                gameDataList.add(game);

                // 保存
                GlobalConfigVo config = GlobalConfigService.GlobalConfig;
                config.getGameSaveBackVoList().add(game);
                GlobalConfigService.updateGlobalConfig(config);

            }
        } catch (IOException e) {
            e.printStackTrace();
            AlertUtil.showErrorAlert("错误", "无法打开添加游戏窗口", e.getMessage());
        }
    }

    @FXML
    private void handleEditGame() {
        int selectedIndex = gameList.getSelectionModel().getSelectedIndex();
        GameSaveBackVo selectedGame = gameList.getSelectionModel().getSelectedItem();
        if (selectedGame != null) {
            try {
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/gameDialog.fxml"));
                Parent root = loader.load();

                GameDialogController controller = loader.getController();
                controller.setDialogStage(new Stage());
                controller.getDialogStage().setTitle("编辑游戏");
                controller.getDialogStage().setScene(new Scene(root));
                controller.getDialogStage().initModality(Modality.WINDOW_MODAL);
                controller.getDialogStage().initOwner(editButton.getScene().getWindow());

                controller.setGame(selectedGame);
                controller.getDialogStage().showAndWait();

                if (controller.isOkClicked()) {
                    GameSaveBackVo updateItem = controller.getGame();
                    gameDataList.set(selectedIndex,updateItem);

                    // 保存
                    GlobalConfigVo config = GlobalConfigService.GlobalConfig;
                    config.getGameSaveBackVoList().set(selectedIndex,updateItem);
                    GlobalConfigService.updateGlobalConfig(config);
                }
            } catch (IOException e) {
                AlertUtil.showErrorAlert("错误", "无法打开编辑游戏窗口", e.getMessage());
            }
        }
    }

    @FXML
    private void handleDeleteGame() {
        int selectedIndex = gameList.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0) {
            if (AlertUtil.showConfirmationAlert("确认删除", "确定要删除选中的游戏吗？")) {
                gameDataList.remove(selectedIndex);
                // 从文件或数据库中删除

                GlobalConfigVo config = GlobalConfigService.GlobalConfig;
                config.getGameSaveBackVoList().remove(selectedIndex);
                GlobalConfigService.updateGlobalConfig(config);
            }
        }
    }

    @FXML
    private void handleBackup() {
        GameSaveBackVo selectedGame = gameList.getSelectionModel().getSelectedItem();
        if (selectedGame != null) {
            try {
                boolean success = GameSaveBackupService.backup(selectedGame);
                if (success) {
                    AlertUtil.showInfoAlert("成功", "备份成功", "游戏存档已成功备份到云端");
                } else {
                    AlertUtil.showErrorAlert("失败", "备份失败", "无法将存档上传到云端");
                }
            } catch (Exception e) {
                e.printStackTrace();
                AlertUtil.showErrorAlert("错误", "备份过程出错", e.getMessage());
            }
        }
    }

    @FXML
    private void handleSync() {
        GameSaveBackVo selectedGame = gameList.getSelectionModel().getSelectedItem();
        if (selectedGame != null) {
            try {
                // 加载存档选择弹窗
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/backupDialog.fxml"));
                Parent root = loader.load();

                BackupDialogController controller = loader.getController();
                Stage dialogStage = new Stage();
                controller.setDialogStage(dialogStage);

                //页面传参
                controller.setGame(selectedGame);

                // 弹窗配置（固定大小、模态、依赖主窗口）
                dialogStage.setScene(new Scene(root));
                dialogStage.initModality(Modality.WINDOW_MODAL);
                dialogStage.initOwner(syncButton.getScene().getWindow());
                dialogStage.setResizable(false); // 禁止拉伸（固定大小）

                controller.loadDate();
                dialogStage.showAndWait();

            } catch (IOException e) {
                e.printStackTrace();
                AlertUtil.showErrorAlert("错误", "无法打开存档选择窗口", e.getMessage());
            }
        }
    }
}